<template>
	<scroll-view class="cat-right-sec" scroll-x scroll-with-animation v-if="currentStr && categoryObj[currentStr] && categoryObj[currentStr][0]">
		<block v-for="(item, index) in categoryObj[currentStr]" :key="index">
			<view class="cat-right-item" :class="{ 'cat-right-act': catRight.current === index }" @click="$switchSCat(index)">
				<text>{{ item.name }}</text>
			</view>
		</block>
	</scroll-view>
</template>

<script>
export default {
	props: {
		parentId: {
			type: [Number, String],
			default: null
		}
	},
	components: {},
	watch: {
		parentId: {
			handler(val) {
				if (val || val === 0) {
					if (val > -1) {
						this.currentStr = '_' + val;
						if (!this.categoryObj[this.currentStr]) {
							this.getDataList();
						}else{
							this.initTab(0)
						}
					}else{
						this.currentStr = ''
					}
				}
			},
			immediate: true
		}
	},
	data() {
		return {
			currentStr: '',
			dataList: [],
			categoryObj: {},
			catRight: {
				current: 0,
				width: 0,
				itemWidth: [],
				scrollLeft: 0
			}
		};
	},

	mounted() {},

	methods: {
		// 获取二级分类
		getDataList() {
			this.$resPost('GetCommonClassify', { type: 1, parent_id: this.parentId, page_size: 100 }).then(({ data }) => {
				let arr = [{ pk_id: null, name: '全部' }];
				if (data && data[0]) {
					this.$set(this.categoryObj, this.currentStr, arr.concat(data));
				} else {
					this.$set(this.categoryObj, this.currentStr, []);
				}
				this.initTab(0)
			});
		},
		// 充值二级分类下标
		initTab () {
			this.catRight.current = 0
			this.catRight.width = 0
		},
		// 点击二级分类
		async $switchSCat(index) {
			if (index === this.catRight.current) return;
			this.catRight.current = index;
			// 如果为0，意味着尚未初始化
			if (this.catRight.width === 0 || this.catRight.itemWidth.length === 0) {
				let catInfo = await this.$getFields('.cat-right-sec');
				let catItemInfo = await this.$getFields('.cat-right-item', true);
				this.catRight = { ...this.catRight, width: catInfo.width, itemWidth: catItemInfo.map(item => item.width) };
			}
			this.catRight.scrollLeft =
				this.catRight.itemWidth.slice(0, index).reduce((sum, item) => sum + item, 0) + this.catRight.itemWidth[index + 1] / 2 - this.catRight.width / 2;
				this.$emit('changeTwoCategory',this.categoryObj[this.currentStr][index].pk_id)
		}
	}
};
</script>

<style scoped lang="scss">
/* 二级分类 */
.cat-right-sec {
	background-color: #fff;
	width: 100%;
	padding: 20rpx 20rpx;
	white-space: nowrap;
	.cat-right-item {
		display: inline-block;
		padding: 0 20rpx;
		line-height: 50rpx;
		border: 1px solid #f5f5f5;
		background-color: #f5f5f5;
		border-radius: 30rpx;
		overflow: hidden;
		margin-right: 20rpx;
		font-size: 28rpx;
		min-width: 90rpx;
		text-align: center;
		&.cat-right-act{
			color: var(--color);
			border-color: var(--color);
		}
	}
}
</style>
